<?php
/**
 * Created by dh2y.
 * Blog: http://blog.csdn.net/sinat_22878395
 * Date: 2020/1/31 14:17
 * For:
 */

namespace app\admin\controller\sys;


use app\admin\model\AuthGroup;
use app\admin\service\sys\AuthGroupService;
use app\admin\service\sys\AuthRuleService;
use app\common\controller\BaseAdmin;

class Role extends BaseAdmin
{
    public function index(){
        if ($this->request->isAjax()){
            //获取搜索条件
            $data =$this->request->except(['page'],'get');

            $model = new AuthGroup();
            $list = $model->withSearch($this->searchFields($data),$this->searchData($data))
                ->order('id','desc')
                ->paginate($data['limit'], false);

            return $this->tableJson($list->getCollection(),$list->total());
        }

        return $this->fetch();
    }

    /**
     * 新建/编辑角色
     * @return string|\think\response\Json
     */
    public function edit(){
        if ($this->request->isAjax()){
            $data = $this->request->param();

            //编辑或者添加数据
            $scene = empty($data['id'])?'add':'edit';
            return json(AuthGroupService::storeRole($data,$scene));
        }

        $id = $this->request->get('id');
        if ($id){
            $list = AuthGroup::where('id', $id)->find();
            $this->assign('list', $list);
        }

        return $this->fetch();
    }

    /**
     * 删除批量删除
     */
    public function remove(){
        if ($this->request->isAjax()){
            $ids = $this->request->param('ids');
            AuthGroup::destroy($ids);
            $this->success('删除成功');
        }else{
            $this->error('非法请求');
        }
    }

    /**
     * 角色审核
     */
    public function change(){
        $id = $this->request->param('id');
        $model = AuthGroup::find($id);
        $model->state = $this->request->param('state');
        if ($model->save()){
            $this->success('操作成功');
        } else {
            $this->error('操作失败');
        }
    }

    /**
     * 权限赋值
     */
    public function access(){
        if ($this->request->isAjax()){

            //将权限数据返回
            if ($this->request->isGet()){
                $all = AuthRuleService::access();
                return json(['code' => 0, 'msg' => '操作成功', 'data' => $all]);
            }

            $data = $this->request->param();
            //权限赋值
            return json(AuthGroupService::storeRole($data,'access'));
        }

        $id = $this->request->get('id');
        if ($id){
            $list = AuthGroup::where('id', $id)->find();
            $this->assign('list', $list);
        }
        return $this->fetch();
    }

}